<template>
  <el-dialog
      :title="id?'修改资源':'新增资源'"
      :visible.sync='show'
      width='30%'
      @open="handlerOpen"
      :before-close='handlerBeforeClose'
      @close="handlerBeforeClose">
    <el-form
        :model='resourceForm'
        ref='resourceForm'
        :rules='resourceFormRules'
        label-width='130px'
        size='medium'>
      <el-form-item label='资源类型' prop='type'>
        <el-radio-group v-model="resourceForm.type">
          <el-radio
              v-for="(item,index) in resourceTypeEnum"
              :key="index"
              :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label='资源名称' prop='name'>
        <el-input v-model="resourceForm.name" placeholder="请输入资源名称"/>
      </el-form-item>
      <el-form-item label='上级资源' prop='parentName'>
        <el-input v-model="resourceForm.parentName"
                  v-popover:resourceRef
                  readonly
                  @click.native="handlerPopoverStyle"/>
        <!-- 父级菜单 -->
        <!-- v-model="resourcePopover" -->
        <el-popover
            ref="resourceRef"
            :width="resourcePopoverWidth"
            placement="bottom"
            trigger="click">
          <el-tree :data="resourceTreeList"
                   :props="defaultProps"
                   ref="resourceTree"
                   node-key="id"
                   highlight-current
                   default-expand-all
                   :expand-on-click-node="false"
                   @current-change="handlerResourceChange">
          </el-tree>
        </el-popover>
      </el-form-item>
      <el-form-item label='路由' v-if="resourceForm.type === 'menu'" prop='route'>
        <el-input v-model="resourceForm.route" placeholder="请输入资源路由"/>
      </el-form-item>
      <el-form-item label='排序号' prop='orderNo'>
        <el-input-number v-model="resourceForm.orderNo" controls-position="right" :min="1" :max="20"/>
      </el-form-item>
      <el-form-item label='授权标识' v-if="resourceForm.type === 'menu'" prop='authCode'>
        <el-input v-model="resourceForm.authCode" placeholder="多个用逗号分隔，如：system.menu:save"/>
      </el-form-item>
      <el-form-item label='图标' prop='icon'>
        <el-input v-model="resourceForm.icon" readonly placeholder="请选择图标" v-popover:iconRef
                  @click.native="handlerPopoverStyle"/>
        <!-- 菜单图标 -->
        <el-popover
            ref="iconRef"
            :width="iconPopoverWidth"
            placement="bottom"
            popper-class="icon-popover-class"
            trigger="click">
          <div>
            <el-button v-for="(item,index) in iconList" :key="index" @click="handlerIconChange(item)">
              <i style="font-size: 20px" :class="item"/>
            </el-button>
          </div>
        </el-popover>
      </el-form-item>
      <el-form-item label='备注' prop='remark'>
        <el-input type="textarea" v-model="resourceForm.remark"/>
      </el-form-item>
    </el-form>
    <div class='footer'>
      <el-button size='medium' type='primary' @click='handlerBeforeClose'>取消</el-button>
      <el-button size='medium' type='success' @click='handlerSubmitForm'>保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { resourceTypeEnum, statusEnum } from '@/enums/CommonEnum'
import ResourceApi from '@/apis/system/ResourceApi'
import { iconList } from '@/plugins/elementui'

export default {
  name: 'ResourceDialog',
  props: {
    show: {
      type: Boolean,
      require: false,
      default: false
    },
    id: {
      type: Number | String,
      required: false
    },
  },
  data () {
    return {
      statusEnum: statusEnum,
      resourceTypeEnum: resourceTypeEnum,
      resourcePopoverWidth: 400,
      iconPopoverWidth: 400,
      resourceList: [],
      iconList: iconList,

      resourceForm: {
        id: null,
        name: null,
        type: resourceTypeEnum[0].value,
        parentName: '顶级菜单',
        parentId: 0,
        systemId: 0,
        route: null,
        authCode: null,
        orderNo: 1,
        icon: null,
        remark: null,
      },
      resourceFormRules: {
        name: { required: true, message: '资源名称不能为空', trigger: 'blur' },
      },
      resourceTreeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }

    }
  },
  computed: {
    size () {
      return this.$store.getters['ElementUI/getSize']
    },
  },
  watch: {
    id (newVal) {
      if (newVal) {
        this.handlerSelectById(this.id)
      }
    },
  },
  methods: {
    /**
     * 选中按钮时触发的事件
     */
    handlerIconChange (iconName) {
      this.resourceForm.icon = iconName
      // 关闭图标popover
      this.$refs.iconRef.doClose()
    },
    /**
     * 当前选中节点变化时触发的事件
     * @param data
     */
    handlerResourceChange (data) {
      this.resourceForm.parentName = data.name
      this.resourceForm.parentId = data.id
      // 关闭菜单树popover
      this.$refs.resourceRef.doClose()
    },
    /**
     * 动态调整el-popover组件的宽度
     * @param $event
     */
    handlerPopoverStyle ($event) {
      const width = $event.currentTarget.clientWidth - 24
      this.resourcePopoverWidth = width
      this.iconPopoverWidth = width
    },
    async handlerSelectById (id) {
      const res = await ResourceApi.selectById(id)
      if (res.code === '0') {
        this.resourceForm = res.data
        if (res.data.parentId === 0) {
          this.resourceForm.parentName = '顶级菜单'
        }
      } else {
        this.$message.error(res.messsage)
      }
    },
    handlerOpen () {
      this.resourceTreeList = []
      this.handlerSelectResourceTreeList()
    },
    /**
     * 查询资源树结构数据
     * @returns {Promise<void>}
     */
    async handlerSelectResourceTreeList () {
      const res = await ResourceApi.selectResourceTreeList({})
      this.resourceTreeList = res.data
    },
    /**
     * dialog关闭
     */
    handlerBeforeClose () {
      this.resourcePopover = false
      this.resourceForm = this.$options.data().resourceForm
      this.$emit('close')
    },
    handlerSubmitForm () {
      this.$refs.resourceForm.validate((valid) => {
        if (!valid) {
          setTimeout(() => {
            const isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
          return false
        }

        if (this.id) {
          this.handlerUpdate()
        } else {
          this.handlerCreate()
        }
      })
    },
    async handlerCreate () {
      const res = await ResourceApi.create(this.resourceForm)
      if (res.code === '0') {
        this.$emit('close')
      } else {
        this.$message.error(res.messsage)
      }
    },
    async handlerUpdate () {
      const res = await ResourceApi.update(this.resourceForm)
      if (res.code === '0') {
        this.$emit('close')
      } else {
        this.$message.error(res.messsage)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.el-dialog {
  .footer {
    text-align: center;
  }

  .el-form {

    .el-form-item {
      /deep/ .el-button {
        padding: 8px;
        margin: 8px 0 0 8px;
      }
    }
  }

  .el-select {
    width: 100%;
  }
}
</style>
